package cpabe;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public class AESCoder {

	private static byte[] getRawKey(byte[] seed) throws Exception {
		KeyGenerator kgen = KeyGenerator.getInstance("AES");
		SecureRandom sr = SecureRandom.getInstance("SHA1PRNG","Crypto"); //PBKDF2
		sr.setSeed(seed);
		kgen.init(128, sr); // 192 and 256 bits may not be available
		SecretKey skey = kgen.generateKey();
		byte[] raw = skey.getEncoded();
		
//		int iterationCount = 1000;
//		int saltLength = 8; // bytes; 64 bits
//		int keyLength = 256;
//		SecureRandom random = new SecureRandom();
//		byte[] salt = new byte[saltLength];
//		random.nextBytes(salt);
//		KeySpec keySpec = new PBEKeySpec(seed.toCharArray(), salt,
//				iterationCount, keyLength);
//		SecretKeyFactory keyFactory = SecretKeyFactory
//				.getInstance("PBKDF2WithHmacSHA1");
//		byte[] raw = keyFactory.generateSecret(keySpec).getEncoded();
//		
//		
		
		return raw;
	}

	public static byte[] encrypt(byte[] seed, byte[] plaintext)
			throws Exception {
		byte[] raw = getRawKey(seed);
		SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
		//SecretKey aesKey = new SecretKeySpec(byte[] raw, "AES");
		Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); //CBC 
		cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
		byte[] encrypted = cipher.doFinal(plaintext);
		return encrypted;
	}

	public static byte[] decrypt(byte[] seed, byte[] ciphertext)
			throws Exception {
		byte[] raw = getRawKey(seed);
		SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
		Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
		cipher.init(Cipher.DECRYPT_MODE, skeySpec);
		byte[] decrypted = cipher.doFinal(ciphertext);
		
		return decrypted;
	}

}